package com.cdp.web.controller.system;

import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.SysEfficiencyAgent;
import com.cdp.common.core.domain.entity.SysMechanicalPerformance;
import com.cdp.common.core.domain.entity.SysWaterReducer;
import com.cdp.framework.web.service.SysPermissionService;
import com.cdp.system.dto.AdditiveDTO;
import com.cdp.system.dto.ExportMechanicalPerformanceExcelDTO;
import com.cdp.system.dto.MechanicalPerformanceQueryDTO;
import com.cdp.system.service.ISysMechanicalPerformanceService;
import com.cdp.system.service.impl.SysPostServiceImpl;
import com.cdp.system.vo.MechanicalPerformanceQueryVO;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 力学性能信息
 */
@RestController
@RequestMapping("/system/mechanical")
public class SysMechanicalPerformanceController {


    @Autowired
    private ISysMechanicalPerformanceService mechanicalPerformanceService;

    @GetMapping("listSysMechanicalPerformance")
    public AjaxResult listSysMechanicalPerformance() {

        List<SysMechanicalPerformance> mechanicalPerformanceList = mechanicalPerformanceService.listSysMechanicalPerformance();
        return AjaxResult.success(mechanicalPerformanceList);
    }

    /**
     * 查询力学性能数据
     *
     * @param mechanicalPerformanceQueryDTO 查询条件 DTO
     * @return AjaxResult 包含查询结果列表
     */
    @PostMapping("queryMistedMechanicalPerformance")
    public AjaxResult queryMistedMechanicalPerformance(@RequestBody MechanicalPerformanceQueryDTO mechanicalPerformanceQueryDTO) {
        // 调用服务层获取查询结果
        List<MechanicalPerformanceQueryVO> result = mechanicalPerformanceService.queryMistedMechanicalPerformance(mechanicalPerformanceQueryDTO);

        // 返回结果
        return AjaxResult.success(result);
    }



    /**
     * 力学性能导出excel
     */
    @PostMapping("exportMechanicalPerformanceExcelText")
    public AjaxResult exportMechanicalPerformanceText(@RequestBody ExportMechanicalPerformanceExcelDTO exportMechanicalPerformanceExcelDTO) {
        List<Integer> mechanicalIds = exportMechanicalPerformanceExcelDTO.getMechanicalIds();
     List<SysMechanicalPerformance> sysMechanicalPerformanceList=   mechanicalPerformanceService.exportMechanicalPerformance(mechanicalIds);


        return AjaxResult.success(sysMechanicalPerformanceList);
    }

    /**
     * 力学性能
     * @param exportMechanicalPerformanceExcelDTO
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */

    @PostMapping("exportAdditiveExcel")
    public ResponseEntity<byte[]> exportAdditiveExcel(@RequestBody ExportMechanicalPerformanceExcelDTO exportMechanicalPerformanceExcelDTO) throws IOException, UnsupportedEncodingException {
        // 获取各类原材料的 ID 列表

        List<Integer> mechanicalIds = exportMechanicalPerformanceExcelDTO.getMechanicalIds();
        List<SysMechanicalPerformance> sysMechanicalPerformanceList=   mechanicalPerformanceService.exportMechanicalPerformance(mechanicalIds);


        // 创建一个 Excel 工作簿
        Workbook workbook = new XSSFWorkbook();
        createMechanicalPerformanceSheet(workbook, sysMechanicalPerformanceList);

        // 将 Excel 数据写入字节数组输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        byteArrayOutputStream.close();

        byte[] excelData = byteArrayOutputStream.toByteArray();
        String fileName = "力学性能数据.xlsx";

        // 对文件名进行 URL 编码
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        // 设置响应头，返回 Excel 文件
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + encodedFileName);
        headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        return ResponseEntity.ok()
                .headers(headers)
                .body(excelData);
    }

    // 工具方法：创力学性能表 sheet

    private void createMechanicalPerformanceSheet(Workbook workbook, List<SysMechanicalPerformance> sysMechanicalPerformanceList) {
        // 创建一个名为 "力学性能" 的工作表
        Sheet sheet = workbook.createSheet("力学性能");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("力学性能ID");
        headerRow.createCell(1).setCellValue("7天抗压强度 (MPa)");
        headerRow.createCell(2).setCellValue("28天抗压强度 (MPa)");
        headerRow.createCell(3).setCellValue("地区名称");
        headerRow.createCell(4).setCellValue("水用量 (kg/m³)");
        headerRow.createCell(5).setCellValue("水泥ID");
        headerRow.createCell(6).setCellValue("水泥用量 (kg/m³)");
        headerRow.createCell(7).setCellValue("粉煤灰ID");
        headerRow.createCell(8).setCellValue("粉煤灰用量 (kg/m³)");
        headerRow.createCell(9).setCellValue("砂ID");
        headerRow.createCell(10).setCellValue("砂用量 (kg/m³)");
        headerRow.createCell(11).setCellValue("石ID");
        headerRow.createCell(12).setCellValue("石用量 (kg/m³)");

        headerRow.createCell(13).setCellValue("减水剂ID");
        headerRow.createCell(14).setCellValue("减水剂掺量 (%)");
        headerRow.createCell(15).setCellValue("增效剂ID");
        headerRow.createCell(16).setCellValue("增效剂掺量 (%)");

        // 填充数据
        int rowNum = 1;
        for (SysMechanicalPerformance performance : sysMechanicalPerformanceList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(safeToString(performance.getMechanicalId()));             // 力学性能ID
            row.createCell(1).setCellValue(safeToString(performance.getCompressiveStrength7d()));   // 7天抗压强度
            row.createCell(2).setCellValue(safeToString(performance.getCompressiveStrength28d()));  // 28天抗压强度
            row.createCell(3).setCellValue(safeToString(performance.getRegionNameStr()));           // 地区名称
            row.createCell(4).setCellValue(safeToString(performance.getWaterContent()));            // 水用量
            row.createCell(5).setCellValue(safeToString(performance.getCementId()));                // 水泥ID
            row.createCell(6).setCellValue(safeToString(performance.getCementContent()));           // 水泥用量
            row.createCell(7).setCellValue(safeToString(performance.getFlyashId()));                // 粉煤灰ID
            row.createCell(8).setCellValue(safeToString(performance.getFlyAshContent()));           // 粉煤灰用量
            row.createCell(9).setCellValue(safeToString(performance.getSandId()));                  // 砂ID
            row.createCell(10).setCellValue(safeToString(performance.getSandContent()));            // 砂用量
            row.createCell(11).setCellValue(safeToString(performance.getStoneId()));                // 石ID
            row.createCell(12).setCellValue(safeToString(performance.getStoneContent()));           // 石用量
            row.createCell(13).setCellValue(safeToString(performance.getReducerId()));                // 减水剂ID
            row.createCell(14).setCellValue(safeToString(performance.getWaterReducerDosage()));            // 减水剂掺量
            row.createCell(15).setCellValue(safeToString(performance.getAgentId()));              // 增效剂ID
            row.createCell(16).setCellValue(safeToString(performance.getEfficiencyAgentDosage()));          // 增效剂掺量
        }
    }

    // 辅助方法：安全地将值转换为字符串
    private String safeToString(Object value) {
        return value == null ? "" : value.toString();
    }




}
